import React, { Component } from 'react';
import Taro, { Config, getCurrentInstance } from '@tarojs/taro';
import { ScrollView, View, Image, Text } from '@tarojs/components'
import { AtMessage } from 'taro-ui'
import classnames from 'classnames'
import './index.scss'
import { connect } from 'react-redux'
import { upDatedMaintainCategory } from '@/store/maintain/action'
import { getSpec, getItemUse } from '@/api/maintain'
type State = {
  scrollTop: number
  goodsList: Array<any>
}

@connect<any>(({ maintain }) => ({ maintain }), _dispatch => ({
  dispatchCategory(data) {
    return _dispatch(upDatedMaintainCategory(data))
  }
}))
export default class MaintainSpecIndex extends Component<any, State> {
  $instance = getCurrentInstance();
  protected params: any
  constructor() {
    super(...arguments)
    this.state = {
      scrollTop: 0,
      goodsList: []
    }
  }
  static options = {
    addGlobalClass: true
  }

  handleClick(item) {
    Taro.navigateTo({
      url: `/pages/detection/detail/index?reportId=${item.reportId}&title=${item.typeLabel}`
    })
  }

  UNSAFE_componentWillMount() {
  }

  componentDidMount() {
    const { params } = this.$instance.router
    this.params = params
    this.getDiyListByCarId(params)
  }

  async getDiyListByCarId(params: any) {
    Taro.showLoading({ title: '加载中'})

    let { projectItemId, jekunModelCode ,mainGoodsId} = params
    try {
      let res = await getSpec({
        projectItemId,
        jekunModelCode,
				mainGoodsId
      })
      if (!res.data.success) throw Error()
      let goodsList = this.forMatData(res.data.data.goodsItems)
      this.setState({
        goodsList
      })
    } catch (error) {
    } finally {
      Taro.hideLoading()
    }

  }

  forMatData(data) {
    data = data.map((i, index) => {
      return {
        ...i,
        checked: false
      }
    })
    return data
  }

  handleChecked(index) {
    let { goodsList } = this.state
    goodsList = goodsList.map((i) => {
      return {
        ...i,
        checked: false
      }
    })
    goodsList[index].checked = true
    this.setState({
      goodsList
    })
    this.getItemUse(goodsList[index].goods.goodsId)
  }

  async getItemUse(goodsId) {
    Taro.showLoading({
      title: '',
      mask: true
    })
    const { projectItemId, jekunModelCode, projectId, isNotChoose, baseServiceId, categoryKey, projectKey, tabKey } = this.params
    let res = await getItemUse({
      goodsId,
      projectItemId,
      jekunModelCode
    })
    let projectItems = res.data.data
    projectItems.baseServiceId = Number(baseServiceId)
    projectItems.projectId = Number(projectId)
    projectItems.isNotChoose = Number(isNotChoose)
    projectItems.categoryKey = Number(categoryKey)
    projectItems.projectKey = Number(projectKey)
    projectItems.tabKey = Number(tabKey)
    projectItems.goodsItems = projectItems.goodsItems.map((i, index) => {
      return {
        ...i,
        tabKey: Number(tabKey),
        categoryKey: Number(categoryKey),
        projectKey: Number(projectKey),
        goodsKey: index
      }
    })
    setTimeout(async () => {
      Taro.hideLoading()
      await this.props.dispatchCategory(projectItems)
      Taro.navigateBack({
        delta: 1
      })
    }, 200)
  }

  render() {
    const scrollStyle = {
      height: '100vh'
    }
    let { goodsList } = this.state
    return (
      <View className='maintain-spec-wrap'>
        <ScrollView className='list' scrollWithAnimation={true} enableBackToTop={true} scrollY={true} style={scrollStyle}>
          <View className="content-wrap">

            {goodsList.map((goods, goodsIndex) =>
              <View className={
                classnames('item-info', {
                  'checked': goods.checked
                })
              } key={String(goods.goodsId)} onClick={this.handleChecked.bind(this, goodsIndex)}>
                <View className="left">
                  <Image className="annual-img" mode="aspectFill" lazyLoad={true} src={goods.goods.thumbnailUrl}></Image>
                </View>
                <View className="right">
                  <Text className="goods-name">{goods.goods.goodsName}</Text>
                  <View className="r-bottom-wrap">
                    <View className="r-bottom-t">
                      {goods.goods.tags && goods.goods.tags.length && <View className="tag">{goods.goods.tags.join(',')}</View>}
                      <Text>已售出{goods.goods.saleCount}件</Text>
                    </View>
                    <View className="r-bottom-b">
                      <View className="r-bottom-b-r">
                        ￥<Text className="price">{Number(goods.goods.salePrice)}</Text>
                        <Text className="origin-price">￥{goods.goods.platformPrice}</Text>
                      </View>
                    </View>
                  </View>
                </View>
              </View>
            )}
          </View>
        </ScrollView>
        <AtMessage />
      </View>
    )
  }
}
